const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

// 所有路由都需要认证
router.use(authenticateToken);

// 获取预算列表
router.get('/', async (req, res) => {
    try {
        const { book_id } = req.query;
        const userId = req.user.user_id;

        let query = `
            SELECT b.*, 
                   COALESCE(SUM(r.amount), 0) as spent_amount,
                   ROUND(COALESCE(SUM(r.amount), 0) / b.amount * 100, 2) as usage_percent
            FROM budgets b
            LEFT JOIN records r ON r.book_id = b.book_id 
                AND r.type = 'expense'
                AND r.is_deleted = 0
                AND r.date >= b.start_date
                AND (b.end_date IS NULL OR r.date <= b.end_date)
                ${book_id ? 'AND (b.category IS NULL OR r.category = b.category)' : ''}
            WHERE b.user_id = ?
        `;
        const params = [userId];

        if (book_id) {
            query += ' AND b.book_id = ?';
            params.push(book_id);
        }

        query += ' GROUP BY b.budget_id ORDER BY b.created_at DESC';

        const [budgets] = await db.query(query, params);

        res.json({
            code: 200,
            data: budgets
        });
    } catch (error) {
        console.error('获取预算列表失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 创建预算
router.post('/', async (req, res) => {
    try {
        const { book_id, budget_name, budget_type, amount, category, start_date, end_date, alert_threshold } = req.body;
        const userId = req.user.user_id;

        // 验证必填字段
        if (!book_id || !amount || !start_date) {
            return res.status(400).json({ code: 400, message: '缺少必要参数' });
        }

        // 自动生成预算名称（如果未提供）
        const finalBudgetName = budget_name || (category ? `${category}预算` : '总预算');
        
        // 自动判断预算类型（如果未提供）
        let finalBudgetType = budget_type || 'monthly';
        if (!budget_type && end_date) {
            finalBudgetType = 'custom';
        }

        const [result] = await db.query(
            `INSERT INTO budgets (user_id, book_id, budget_name, budget_type, amount, category, start_date, end_date, alert_threshold)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
            [userId, book_id, finalBudgetName, finalBudgetType, amount, category || null, start_date, end_date || null, alert_threshold || 80]
        );

        res.json({
            code: 200,
            message: '预算创建成功',
            data: { budget_id: result.insertId }
        });
    } catch (error) {
        console.error('创建预算失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误', error: error.message });
    }
});

// 更新预算
router.put('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const { budget_name, amount, alert_threshold, is_enabled } = req.body;
        const userId = req.user.user_id;

        await db.query(
            `UPDATE budgets 
             SET budget_name = COALESCE(?, budget_name),
                 amount = COALESCE(?, amount),
                 alert_threshold = COALESCE(?, alert_threshold),
                 is_enabled = COALESCE(?, is_enabled)
             WHERE budget_id = ? AND user_id = ?`,
            [budget_name, amount, alert_threshold, is_enabled, id, userId]
        );

        res.json({ code: 200, message: '预算更新成功' });
    } catch (error) {
        console.error('更新预算失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 删除预算
router.delete('/:id', async (req, res) => {
    try {
        const { id } = req.params;
        const userId = req.user.user_id;

        await db.query('DELETE FROM budgets WHERE budget_id = ? AND user_id = ?', [id, userId]);

        res.json({ code: 200, message: '预算删除成功' });
    } catch (error) {
        console.error('删除预算失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

// 检查预算预警
router.get('/alerts', async (req, res) => {
    try {
        const { book_id } = req.query;
        const userId = req.user.user_id;

        let query = `
            SELECT b.*, 
                   COALESCE(SUM(r.amount), 0) as spent_amount,
                   ROUND(COALESCE(SUM(r.amount), 0) / b.amount * 100, 2) as usage_percent
            FROM budgets b
            LEFT JOIN records r ON r.book_id = b.book_id 
                AND r.type = 'expense'
                AND r.is_deleted = 0
                AND r.date >= b.start_date
                AND (b.end_date IS NULL OR r.date <= b.end_date)
                ${book_id ? 'AND (b.category IS NULL OR r.category = b.category)' : ''}
            WHERE b.user_id = ? AND b.is_enabled = 1
        `;
        const params = [userId];

        if (book_id) {
            query += ' AND b.book_id = ?';
            params.push(book_id);
        }

        query += ' GROUP BY b.budget_id HAVING usage_percent >= b.alert_threshold';

        const [alerts] = await db.query(query, params);

        res.json({
            code: 200,
            data: alerts.map(alert => ({
                ...alert,
                alert_level: alert.usage_percent >= 100 ? 'danger' : 'warning',
                alert_message: alert.usage_percent >= 100 
                    ? `预算"${alert.budget_name}"已超支${(alert.usage_percent - 100).toFixed(1)}%！`
                    : `预算"${alert.budget_name}"已使用${alert.usage_percent}%，即将超支！`
            }))
        });
    } catch (error) {
        console.error('检查预算预警失败:', error);
        res.status(500).json({ code: 500, message: '服务器错误' });
    }
});

module.exports = router; 